package com.ruoyi.asset.service.impl;

import java.io.File;
import java.time.LocalDate;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.asset.common.AssetStatusType;

import com.ruoyi.asset.common.PDFUtils;
import com.ruoyi.asset.domain.AssetTransactionRecord;
import com.ruoyi.asset.domain.DisposalRecord;
import com.ruoyi.asset.domain.MaintenanceRecord;
import com.ruoyi.asset.mapper.AssetTransactionRecordMapper;
import com.ruoyi.asset.mapper.DisposalRecordMapper;
import com.ruoyi.asset.mapper.MaintenanceRecordMapper;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.asset.mapper.FixedAssetsMapper;
import com.ruoyi.asset.domain.FixedAssets;
import com.ruoyi.asset.service.IFixedAssetsService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 固定资产信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-06
 */
@Service
public class FixedAssetsServiceImpl extends ServiceImpl<FixedAssetsMapper, FixedAssets> implements IFixedAssetsService {
    @Autowired
    private FixedAssetsMapper fixedAssetsMapper;


    @Autowired
    private AssetTransactionRecordMapper assetTransactionRecordMapper;


    @Autowired
    private MaintenanceRecordMapper maintenanceRecordMapper;

    @Autowired
    private DisposalRecordMapper disposalRecordMapper;


    /**
     * 查询固定资产信息
     *
     * @param assetNumber 固定资产信息主键
     * @return 固定资产信息
     */
    @Override
    public FixedAssets selectFixedAssetsByassetNumber(String assetNumber) {
        return fixedAssetsMapper.selectFixedAssetsByassetNumber(assetNumber);
    }

    /**
     * 查询固定资产信息列表
     *
     * @param fixedAssets 固定资产信息
     * @return 固定资产信息
     */
    @Override
    public List<FixedAssets> selectFixedAssetsList(FixedAssets fixedAssets) {
        return fixedAssetsMapper.selectFixedAssetsList(fixedAssets);
    }

    /**
     * 新增固定资产信息
     *
     * @param fixedAssets 固定资产信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertFixedAssets(FixedAssets fixedAssets) {

        String assetNumber = fixedAssets.getAssetNumber();
        if (assetNumber.contains("/")) {
            throw new UtilException("/为非法字符");
        }


        //获取使用人
//        String username = fixedAssets.getUserName();
        String userId = fixedAssets.getUserId();
        boolean userIdNotEmpty = StringUtils.isNotEmpty(userId);
        if ("".equals(userId) || userId == null) {
            userId = "无";
            fixedAssets.setUserId("无");
        }

/*
        if ((StringUtils.isEmpty(username) && userIdNotEmpty) ||
                (StringUtils.isNotEmpty(username) && StringUtils.isEmpty(userId))) {
            throw new UtilException("工号和使用人必须同时填写");
        }
*/
        //查询资产编号是否存在
        LambdaQueryWrapper<FixedAssets> fixedAssetsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fixedAssetsLambdaQueryWrapper.eq(FixedAssets::getAssetNumber, fixedAssets.getAssetNumber());
        Integer integer = fixedAssetsMapper.selectCount(fixedAssetsLambdaQueryWrapper);
        if (integer > 0) {
            throw new UtilException("固定资产编号已存在");
        }


/*        //判断使用人是否为空，如果使用人不为空直接插入领用归还记录表
        if (userIdNotEmpty) {
            AssetTransactionRecord atr = new AssetTransactionRecord();
            atr.setTransactionId(String.valueOf(UUID.randomUUID()));
            atr.setAssetNumber(fixedAssets.getAssetNumber());
            atr.setTransactionType("0");
            atr.setTransactionDate(new Date());
            atr.setBorrower(userId);
            assetTransactionRecordMapper.insertAssetTransactionRecord(atr);
        }*/


        return fixedAssetsMapper.insert(fixedAssets);
    }

    /**
     * 修改固定资产信息
     *
     * @param fixedAssets 固定资产信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateFixedAssets(FixedAssets fixedAssets) {
/*
        //获取使用人
        String username = fixedAssets.getUserName();
        String userId = fixedAssets.getUserId();
        boolean userIdNotEmpty = StringUtils.isNotEmpty(userId);*/
/*        if (userId.equals("")|| userId == null) {
            userId = "无";
            fixedAssets.setUserId("无");
        }*/
/*        if (userId.equals("")) {
            userId = "无";
            fixedAssets.setUserId("无");
        }*/

/*        if ((StringUtils.isEmpty(username) && !userId.equals("无")) ||
                (StringUtils.isNotEmpty(username) && userId.equals("无"))) {
            throw new UtilException("工号和使用人必须同时填写");
        }*/

        //获取资产编号
        String assetNumber = fixedAssets.getAssetNumber();
        //查询老的资产信息
        LambdaQueryWrapper<FixedAssets> fixedAssetsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fixedAssetsLambdaQueryWrapper.eq(FixedAssets::getAssetNumber, assetNumber);
        FixedAssets oldFixedAssets = fixedAssetsMapper.selectOne(fixedAssetsLambdaQueryWrapper);
        //获取新的资产信息状态
        String newAssetStatus = fixedAssets.getAssetStatus();
        //获取工号
        String newUserId = fixedAssets.getUserId();
 /*       if (newUserId.equals("")) {
            newUserId = "无";
            fixedAssets.setUserId("无");
        }*/
        String oldUserId = oldFixedAssets.getUserId();
        //报废状态无法修改信息
        if (newAssetStatus.equals(AssetStatusType.SCRAPPED)) {
            throw new UtilException("报废状态无法修改信息");
        }
/*        //如果是待报废状态下
        if (newAssetStatus.equals(AssetStatusType.TO_BE_SCRAPPED)) {
            if (!newUserId.equals("无") || !oldUserId.equals("无")) {
                throw new UtilException("待报废状态下不能有有资产转移");
            }
        }
        //如果是维修状态下
        if (newAssetStatus.equals(AssetStatusType.MAINTENANCE)) {
            if (!newUserId.equals(oldUserId)) {
                throw new UtilException("维修状态下资产不能转移");
            }
        }*/
        /*if (newAssetStatus.equals(AssetStatusType.NORMAL)) {
            //如果新的老的工号都不是空的旧先归还后创建新领用
            if (!newUserId.equals("无") && !oldUserId.equals("无")) {
                if (!newUserId.equals(oldUserId)) {
                    //查询已存在的领用记录
                    LambdaQueryWrapper<AssetTransactionRecord> atrQuery = new LambdaQueryWrapper<>();
                    atrQuery.eq(AssetTransactionRecord::getAssetNumber, assetNumber);
                    atrQuery.eq(AssetTransactionRecord::getBorrower, oldUserId);
                    atrQuery.and(qw ->qw.eq(AssetTransactionRecord::getTransactionType, AssetTransactionRecordType.CLAIM).
                            or().eq(AssetTransactionRecord::getTransactionType, AssetTransactionRecordType.BORROW));
                    AssetTransactionRecord oldatr = assetTransactionRecordMapper.selectOne(atrQuery);
*//*                    if (oldatr != null) {
                        //设置归还人更新归还记录
                        oldatr.setTransactionType(AssetTransactionRecordType.SLUGGISH);
                        oldatr.setReturnDate(new Date());
                        oldatr.setReturner(oldUserId);
                        assetTransactionRecordMapper.updateById(oldatr);
                    }*//*
                    //创建新领用人记录
                    AssetTransactionRecord newatr = new AssetTransactionRecord();
                    newatr.setTransactionId(UUID.randomUUID().toString());
                    newatr.setAssetNumber(assetNumber);
                    newatr.setTransactionType(AssetTransactionRecordType.CLAIM);
                    newatr.setTransactionDate(new Date());
                    newatr.setBorrower(newUserId);
                    assetTransactionRecordMapper.insert(newatr);
                }
            }
            //如果新的是空的直接更新已存在领用记录表
            if (newUserId.equals("无") && !oldUserId.equals("无")) {
                //查询已存在的领用记录
                LambdaQueryWrapper<AssetTransactionRecord> atrQuery = new LambdaQueryWrapper<>();
                atrQuery.eq(AssetTransactionRecord::getAssetNumber, assetNumber);
                atrQuery.eq(AssetTransactionRecord::getBorrower, oldUserId);
                atrQuery.eq(AssetTransactionRecord::getTransactionType, AssetTransactionRecordType.CLAIM).
                        or().eq(AssetTransactionRecord::getTransactionType, AssetTransactionRecordType.BORROW);
                AssetTransactionRecord oldatr = assetTransactionRecordMapper.selectOne(atrQuery);
                if (oldatr != null) {
                    oldatr.setTransactionType(AssetTransactionRecordType.SLUGGISH);
                    //设置归还人更新归还记录
                    oldatr.setReturnDate(new Date());
                    oldatr.setReturner(oldUserId);
                    assetTransactionRecordMapper.updateById(oldatr);
                }
            }
            //如果旧的是空的新的不是空查询是否存在
            if (!newUserId.equals("无") && oldUserId.equals("无")) {
                //查询已存在的领用记录
                LambdaQueryWrapper<AssetTransactionRecord> atrQuery = new LambdaQueryWrapper<>();
                atrQuery.eq(AssetTransactionRecord::getAssetNumber, assetNumber);
                atrQuery.eq(AssetTransactionRecord::getTransactionType, AssetTransactionRecordType.CLAIM).
                        or().eq(AssetTransactionRecord::getTransactionType, AssetTransactionRecordType.BORROW);
                AssetTransactionRecord oldatr = assetTransactionRecordMapper.selectOne(atrQuery);
                if (oldatr != null) {
                    throw new UtilException("该固定资产状态为领用或借用，请核对领用归还记录");
                }
                //创建新领用人记录
                AssetTransactionRecord newatr = new AssetTransactionRecord();
                newatr.setTransactionId(UUID.randomUUID().toString());
                newatr.setAssetNumber(assetNumber);
                newatr.setTransactionType(AssetTransactionRecordType.CLAIM);
                newatr.setTransactionDate(new Date());
                newatr.setBorrower(newUserId);
                assetTransactionRecordMapper.insert(newatr);
            }
        }*/

        return fixedAssetsMapper.updateById(fixedAssets);
    }

    /**
     * 批量删除固定资产信息
     *
     * @param assetNumbers 需要删除的固定资产信息主键
     * @return 结果
     */
    @Override
    public int deleteFixedAssetsByassetNumbers(String assetNumbers) {
        String[] strings = Convert.toStrArray(assetNumbers);
        for (String assetNumber : strings) {
            FixedAssets fixedAssets = fixedAssetsMapper.selectById(assetNumber);
            if (!fixedAssets.getAssetStatus().equals(AssetStatusType.NORMAL)) {
                throw new UtilException(assetNumber + "不是正常状态下的资产无法删除");
            }
            LambdaQueryWrapper<AssetTransactionRecord> atrlqWrapper = new LambdaQueryWrapper<>();
            atrlqWrapper.eq(AssetTransactionRecord::getAssetNumber, assetNumber);
            Integer atrCount = assetTransactionRecordMapper.selectCount(atrlqWrapper);
            if (atrCount > 0) {
                throw new UtilException(assetNumber + "产生过领用归还记录的无法删除");
            }

            LambdaQueryWrapper<MaintenanceRecord> mrlqw = new LambdaQueryWrapper<>();
            mrlqw.eq(MaintenanceRecord::getAssetNumber, assetNumber);
            Integer mrCount = maintenanceRecordMapper.selectCount(mrlqw);
            if (mrCount > 0) {
                throw new UtilException(assetNumber + "产生过维修记录无法删除");
            }


            LambdaQueryWrapper<DisposalRecord> drlqw = new LambdaQueryWrapper<>();
            drlqw.eq(DisposalRecord::getAssetNumber, assetNumber);
            Integer drCount = disposalRecordMapper.selectCount(drlqw);
            if (drCount > 0) {
                throw new UtilException(assetNumber + "产生过保费记录无法删除");
            }


        }


        return fixedAssetsMapper.deleteFixedAssetsByassetNumbers(strings);
    }

    /**
     * 删除固定资产信息信息
     *
     * @param assetNumber 固定资产信息主键
     * @return 结果
     */
    @Override
    public int deleteFixedAssetsByassetNumber(String assetNumber) {
        FixedAssets fixedAssets = fixedAssetsMapper.selectById(assetNumber);
        if (!fixedAssets.getAssetStatus().equals(AssetStatusType.NORMAL)) {
            throw new UtilException(assetNumber + "不是正常状态下的资产无法删除");
        }
        LambdaQueryWrapper<AssetTransactionRecord> atrlqWrapper = new LambdaQueryWrapper<>();
        atrlqWrapper.eq(AssetTransactionRecord::getAssetNumber, assetNumber);
        Integer integer = assetTransactionRecordMapper.selectCount(atrlqWrapper);
        if (integer > 0) {
            throw new UtilException(assetNumber + "产生过领用归还记录的无法删除");
        }

        LambdaQueryWrapper<MaintenanceRecord> mrlqw = new LambdaQueryWrapper<>();
        mrlqw.eq(MaintenanceRecord::getAssetNumber, assetNumber);
        Integer mrCount = maintenanceRecordMapper.selectCount(mrlqw);
        if (mrCount > 0) {
            throw new UtilException(assetNumber + "产生过维修记录无法删除");
        }

        LambdaQueryWrapper<DisposalRecord> drlqw = new LambdaQueryWrapper<>();
        drlqw.eq(DisposalRecord::getAssetNumber, assetNumber);
        Integer drCount = disposalRecordMapper.selectCount(drlqw);
        if (drCount > 0) {
            throw new UtilException(assetNumber + "产生过报废记录无法删除");
        }
        return fixedAssetsMapper.deleteFixedAssetsByassetNumber(assetNumber);
    }

    @Override
    public File printFixedAssetsInfo(String id) {
        FixedAssets fixedAssets = fixedAssetsMapper.selectById(id);

        if (fixedAssets == null) {
            throw new UtilException("该物料编码不存在");
        }

        String date = DateUtils.getDate();

        if (fixedAssets.getUserId().equals("无")) {
            throw new UtilException("使用人为空不能打印");
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("资产名称", fixedAssets.getAssetName());
        map.put("资产编号", fixedAssets.getAssetNumber());
        map.put("规格型号", StringUtils.isNotEmpty(fixedAssets.getAssetModel()) ? fixedAssets.getAssetModel() : "");
        map.put("使用部门", fixedAssets.getDepartment());
        map.put("使用时间", date);
        map.put("使用人", fixedAssets.getUserId() + "_" + fixedAssets.getUserName());

        List<Map<String, String>> hashMaps = new ArrayList<>();
        hashMaps.add(map);
        File file = PDFUtils.createPDF(fixedAssets.getAssetNumber(), hashMaps);
//        byte[] bytes=null;
//        try {
//             bytes = PDFUtils.convertPdfToBytes(file);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

//        try {
//            PDFUtils.PDFprint(file);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        return file;
    }


    @Override
    public File printFixedAssetsInfoList(String ids) {
        String[] strings = Convert.toStrArray(ids);
        ArrayList<Map<String, String>> maps = new ArrayList<Map<String, String>>();
        if (ids != null || ids != "") {
            for (int i = 0; i < strings.length; i++) {
                FixedAssets fixedAssets = fixedAssetsMapper.selectById(strings[i]);
                if (fixedAssets == null) {
                    throw new UtilException("该物料编码不存在");
                }
                String date = DateUtils.getDate();
                if (fixedAssets.getUserId().equals("无")) {
                    throw new UtilException("使用人为空不能打印");
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("资产名称", fixedAssets.getAssetName());
                map.put("资产编号", fixedAssets.getAssetNumber());
                map.put("规格型号", StringUtils.isNotEmpty(fixedAssets.getAssetModel()) ? fixedAssets.getAssetModel() : "");
                map.put("使用部门", fixedAssets.getDepartment());
                map.put("使用时间", date);
                map.put("使用人", fixedAssets.getUserId() + "_" + fixedAssets.getUserName());
                maps.add(map);
            }
        }

        File file = PDFUtils.createPDF(ids, maps);
//        try {
//            PDFUtils.PDFprint(file);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        return file;
    }

    @Override
    public List<FixedAssets> getStatementList(FixedAssets fixedAssets) {
        Object beginPurchaseDate = fixedAssets.getParams().get("beginPurchaseDate");
        Object endPurchaseDate = fixedAssets.getParams().get("endPurchaseDate");

        if (beginPurchaseDate == null || beginPurchaseDate.equals("") || endPurchaseDate == null || endPurchaseDate.equals("")) {
            Map<String, Object> objectObjectMap = new HashMap<>();
            LocalDate date = LocalDate.now();
            objectObjectMap.put("beginPurchaseDate", date.minusYears(1).toString());
            objectObjectMap.put("endPurchaseDate", date.toString());
            fixedAssets.setParams(objectObjectMap);
        }
        return fixedAssetsMapper.selectFixedAssetsCountList(fixedAssets);
    }
}
